import { useEffect, useState } from "react";
import { request } from "src/request";

export type MixIngredient = {
  id?: string;
  name: string;
  remark?: string;
  formulasCount?: number;
}

export function useMixIngredients(): [MixIngredient[], () => Promise<void>, boolean] {
  const [mixIngredients, setMixIngredients] = useState<MixIngredient[]>([]);
  const [loading, setLoading] = useState(false);

  const fetchMixIngredients = async () => {
    setLoading(true);
    try {
      const response = await request.get('/mix-ingredient');
      setMixIngredients(response.data as MixIngredient[]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchMixIngredients();
  }, []);

  return [mixIngredients, fetchMixIngredients, loading];
}

export function useMixIngredient(id): [MixIngredient | undefined, () => Promise<void>, boolean] {
  const [mixIngredient, setMixIngredient] = useState<MixIngredient>();
  const [loading, setLoading] = useState(false);

  const fetchMixIngredient = async () => {
    setLoading(true);
    try {
      const response = await request.get(`/mix-ingredient/${id}`);
      setMixIngredient(response.data as MixIngredient);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchMixIngredient();
  }, []);

  return [mixIngredient, fetchMixIngredient, loading];
}
